package com.xcx.robot.util;


import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import gui.ava.html.image.generator.HtmlImageGenerator;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

/**
 * @Author: 邢晨旭
 * @Date: 2021/6/9 11:17
 * @Description:
 */
@Slf4j
public class FreemarkerUtils {


    private static String getTemplate(String template, Map<String, Object> map) throws IOException, TemplateException {
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_25);
        String templatePath = FreemarkerUtils.class.getResource("/").getPath() + "/templates";
        cfg.setDirectoryForTemplateLoading(new File("ftl"));
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        cfg.setLogTemplateExceptions(false);
        Template temp = cfg.getTemplate(template);
//        FreeMarkerConfigurer freeMarkerConfigurer = ApplicationContextHelper.getBean(FreeMarkerConfigurer.class);
//        Template temp = freeMarkerConfigurer.getConfiguration().getTemplate(template);
        StringWriter stringWriter = new StringWriter();
        temp.process(map, stringWriter);
        stringWriter.flush();
        stringWriter.close();
        return stringWriter.getBuffer().toString();
    }

    public static BufferedImage turnImage(String template, Map<String, Object> map) {
        try {
            String html = getTemplate(template, map);
//            System.out.println(html);
            HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
            imageGenerator.loadHtml(html);
            BufferedImage img = imageGenerator.getBufferedImage();
//            ImageIO.write(img, "png", new File("test1.png"));
            return img;
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }


}
